package com.xysq.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rockcent.action.AppAction;
import com.rockcent.action.CallbackListener;
import com.rockcent.action.impl.AppActionImpl;
import com.rockcent.model.CouponModel;
import com.rockcent.model.constant.BizStateType;
import com.rockcent.model.constant.StateType;
import com.umeng.analytics.MobclickAgent;
import com.xysq.activity.ImagesActivity;
import com.xysq.lemon.R;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.UseUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.widget.XYBannerHelper;
import com.xysq.widget.XYBannerInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link GoodsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link GoodsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GoodsFragment extends Fragment implements XYBannerHelper.OnItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String couponModelId = "couponModelId";

    // TODO: Rename and change types of parameters
    private int id;
    TextView originalPriceTxt;
    TextView priceTxt;
    TextView nameTxt;
    TextView saleCountTxt;
    TextView timeTxt;
    TextView useInstructionTxt;
    WebView detailsWebView;
    LinearLayout loadingLayout;
    LinearLayout reloadingLayout;
    LinearLayout bottomLayout;

    private XYBannerHelper goodsBanner;
    private String picUrls;
    private String picUrl[];
    private int picSize;
    StateType stateType;
    BizStateType bizStateType;
    boolean firstActive = true;

    public AppAction appAction;

    private OnFragmentInteractionListener mListener;
    public static final String COUPON_MODEL = "couponModel";

    public static GoodsFragment newInstance(int mCouponModelId) {
        GoodsFragment fragment = new GoodsFragment();
        Bundle args = new Bundle();
        args.putInt(couponModelId, mCouponModelId);
        fragment.setArguments(args);
        return fragment;
    }

    public GoodsFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getInt(couponModelId);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_goods, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
//        loadData();
    }

    private void loadData() {
        loadDetail();
    }

    private void loadDetail() {
        appAction.viewCouponModel(id, UserInfoKeeper.readPhoneNumber(getActivity()), 1, new CallbackListener<CouponModel>() {
            @Override
            public void onSuccess(CouponModel data) {
                if(isAdded()) {
                    nameTxt.setText(data.getName());
                    Log.e("+++价格", data.getEstimateAmount() + "");
                    priceTxt.setText("￥" + UseUtil.handlePrice(data.getEstimateAmount()));
                    originalPriceTxt.setText("￥" + UseUtil.handlePrice(data.getFaceValue()));
                    timeTxt.setText(String.valueOf(getResources().getString(R.string.txt_end_date_pre) + timeChangeFormat(data.getUseEndTime())));
                    useInstructionTxt.setText(data.getExplanation());
                    String url = data.getIntroduceHTML();
//                    url = url.replaceAll("style=\"(.*?)\"", "");
                    url = "<style>img{max-width:100%;}</style>" + url;
                    detailsWebView.loadDataWithBaseURL("", url, "text/html", "UTF-8", "");
                    detailsWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                    saleCountTxt.setText(String.valueOf(getResources().getString(R.string.txt_number_all_pre) + String.valueOf(data.getSaleCount())));
                    picUrls = data.getPicUrl();
                    stateType = data.getState();
                    bizStateType = data.getBizState();
                    Button stateBtn = (Button) getActivity().findViewById(R.id.btn_buy_now);
                    if (data.getEstimateAmount() == 0) {
                        stateBtn.setEnabled(false);
                    } else if (bizStateType == BizStateType.UNDERCARRIAGE) {
                        stateBtn.setText("已下架");
                        stateBtn.setClickable(false);
                        stateBtn.setBackgroundColor(getResources().getColor(R.color.gray_1));
                    } else if (data.getUseEndTime() < System.currentTimeMillis()) {
                        stateBtn.setText("已过期");
                        stateBtn.setClickable(false);
                        stateBtn.setBackgroundColor(getResources().getColor(R.color.gray_1));
                    } else if (stateType == StateType.STOPED) {
                        stateBtn.setText("已停用");
                        stateBtn.setClickable(false);
                        stateBtn.setBackgroundColor(getResources().getColor(R.color.gray_1));
                    } else if (Integer.parseInt(data.getIssueCount()) - data.getLockedCount() - data.getSaleCount() <= 0) {
                        stateBtn.setText("已售完");
                        stateBtn.setClickable(false);
                        stateBtn.setBackgroundColor(getResources().getColor(R.color.gray_1));
                    } else {
                        stateBtn.setEnabled(true);
                    }
                    if (picUrls != null) {
                        picUrl = split(picUrls);
                        picSize = picUrl.length;
                    }
                    originalPriceTxt.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                    getHeadPic();
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.w(errorCode, message);
                reloadingLayout.setVisibility(View.VISIBLE);
                bottomLayout.setVisibility(View.GONE);
            }
        });
    }

    private void initView() {
        appAction = AppActionImpl.getInstance(getActivity(), PropertiesUtil.getXyapiAddress(), PropertiesUtil.getQkapiAddress());
        originalPriceTxt = (TextView) getView().findViewById(R.id.txt_original_price);
        priceTxt = (TextView) getView().findViewById(R.id.txt_price);
        nameTxt = (TextView) getView().findViewById(R.id.txt_introduce);
        saleCountTxt = (TextView) getView().findViewById(R.id.txt_sale_count);
        timeTxt = (TextView) getView().findViewById(R.id.txt_time);
        useInstructionTxt = (TextView) getView().findViewById(R.id.txt_use_instruction);
        detailsWebView = (WebView) getView().findViewById(R.id.webview_details);
        loadingLayout = (LinearLayout) getActivity().findViewById(R.id.layout_loading);
        reloadingLayout = (LinearLayout) getActivity().findViewById(R.id.layout_reloading);
        bottomLayout = (LinearLayout) getActivity().findViewById(R.id.layout_bottom);
        reloadingLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reloadingLayout.setVisibility(View.GONE);
                loadingLayout.setVisibility(View.VISIBLE);
                loadData();
            }
        });
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onItemClick(int index, View v) {
        Intent intent = new Intent(getActivity(), ImagesActivity.class);
        intent.putExtra(ImagesActivity.PARAM_CURRENT_POSITION, index);
        ArrayList picList = new ArrayList<>();
        for(String pic : picUrl) {
            picList.add(pic);
        }
        intent.putStringArrayListExtra(ImagesActivity.PARAM_IMAGE_URLS, picList);
        getActivity().startActivity(intent);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    private String[] split(String picUrls) {
        String[] picUrl = picUrls.split(";");
        return picUrl;
    }

    private void getHeadPic() {
        ArrayList<XYBannerInfo> infos = new ArrayList<XYBannerInfo>() {{
            for (int i = 0; i < picSize; i++) {
                add(new XYBannerInfo("", PropertiesUtil.getImageServer() + picUrl[i]));
            }
        }};
        goodsBanner = new XYBannerHelper(getActivity());
        goodsBanner.setBannerInfo(infos);
        goodsBanner.startAutoRoll();
        goodsBanner.setOnItemClickCallback(this);
        loadingLayout.setVisibility(View.GONE);
        bottomLayout.setVisibility(View.VISIBLE);
    }

    private String timeChangeFormat(Long data) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String time = format.format(data);
        return time;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (goodsBanner != null) {
            goodsBanner.destroyHelper();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (goodsBanner != null) {
            goodsBanner.stopAutoRoll();
        }
        MobclickAgent.onPageEnd("商品详情页");
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (goodsBanner != null & firstActive == false) {
//            goodsBanner.startAutoRoll();
//        }
//        firstActive = false;
        MobclickAgent.onPageStart("商品详情页");
        loadData();
    }
}
